//
//  SHOAuthViewController.swift
//  SHWeibo01
//
//  Created by 卫平玉 on 16/7/21.
//  Copyright © 2016年 卫平玉. All rights reserved.
//

import UIKit
import SVProgressHUD
class SHOAuthViewController: UIViewController {

    override func loadView() {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(APPREDIRECT_URI)"
        let url = NSURL(string: urlString)
        
        guard let u = url else{
            return
        }
        
       let request = NSURLRequest(URL: u)
        
        webView.loadRequest(request)
        
        webView.delegate = self
        
        view = webView
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        
        progressView.removeView()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }
    
    func setupUI(){
        
        view.backgroundColor = UIColor.whiteColor()
        
        setupNav()
        
        navigationController?.view.insertSubview(progressView, belowSubview: navigationController!.navigationBar)
    }
    
    func setupNav(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", imgName: nil, target: self, action: "cancelClick")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", imgName: nil, target: self, action: "autoFill")
        
        navigationItem.title = "微博登录"
    }
    
    @objc private func cancelClick(){
    
    dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func autoFill(){
        
        let jsString = "document.getElementById('userId').value='\(wbName)',document.getElementById('passwd').value='\(wbPasswd)'"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
   private lazy var webView: UIWebView = UIWebView()
    
    private lazy var progressView: SHOAuthProgressView = SHOAuthProgressView()

}


extension SHOAuthViewController: UIWebViewDelegate {
    
    
    func webViewDidStartLoad(webView: UIWebView) {
        
        progressView.startAnim()
        
//        SVProgressHUD.show()
        
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
        progressView.stopAnim()
        
//        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
        
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL?.absoluteString
        
        if let u = urlString where u.hasPrefix(APPREDIRECT_URI){
            
            let query = request.URL?.query
            
            if let q = query{
                let code = q.substringFromIndex("code=".endIndex)
                print(code)
                
                SHUserAccountViewModel.sharedTools.loadUserAccount(code, isSuccess: { (isSuccess) -> () in
                    
                    print(isSuccess)
                    if !isSuccess{
                        
                        print("请求失败")
                        return
                    }
                    
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        
                        NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootViewControllerNoti, object: nil)
                    })
                })
                
                return false
            }
            
           
        }
        
        return true
    }
}


extension SHOAuthViewController{
    
    func getUserAccount(code: String){
        
        SHNetworkTools.sharedTools.oauthLoadUserAccount(code, success: { (response) -> () in
            guard let res = response as? [String: AnyObject] else{
                return
            }
            
            let userAccount = SHUserAccount(dict: res)
            
            self.getUserInfo(userAccount)
            }) { (error) -> () in
                print("请求失败\(error)")
        }
    }
    
    func getUserInfo(userAccount: SHUserAccount){
        
        SHNetworkTools.sharedTools.oauthLoadUserInfo(userAccount, success: { (response) -> () in
            guard let res = response as? [String: AnyObject] else{
                return
            }
            
            userAccount.screen_name = res["screen_name"] as? String
            
            userAccount.avatar_large = res["avatar_large"] as? String
            
            print(userAccount)
            
            }) { (error) -> () in
                print("请求失败\(error)")
                
        }
        
    }
}